package cc.rengu.redp.bizimpl.upmp.controller;

import cc.rengu.igas.bomp.facade.BompMchntQueryService;
import cc.rengu.igas.bomp.facade.request.MchntAreaListQueryRequest;
import cc.rengu.igas.bomp.facade.request.MchntInfoListQueryRequest;
import cc.rengu.igas.momp.facade.bean.*;
import cc.rengu.igas.momp.facade.request.*;
import cc.rengu.igas.momp.facade.response.*;
import cc.rengu.igas.momp.facade.result.Result;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpOrgTreeInfo;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpSysParam;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpUserInfo;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.*;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.common.controller.BaseController;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.properties.RedpProperties;
import cc.rengu.redp.common.utils.SpringContextUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags = "营销管理:银行对收银员营销活动管理")
@Slf4j
@RestController
@RequestMapping("/admin/market/cashierManager")
public class CashierMarketManagerController extends BaseController {

    private static final String point = ".";
    @Autowired
    private IUpmpOrganizationService organizationService;

    @Autowired
    private IUpmpSysSeqService sysSeqService;

    @Autowired
    private IUpmpSysParamService upmpSysParamService;

    @Autowired
    private IUpmpUserInfoService userService;

//    dubbo服务
    @Autowired
    private CommissionMarketService marketService;

    @Autowired
    private ICustomerMarketService customerMarketService;

    @Autowired
    private ICashierMarketManagerService cashierService;

    @Autowired
    private IUpmpBMchntBaseInfoService bMchntBaseInfoService;

//    @DubboReference(version = "2.2.0", url = "dubbo://172.17.100.9:62132", check = false)
    @DubboReference(version = "${dubbo.protocol.version}", check = false)
    private BompMchntQueryService bompMchntQueryService;

    private final static String commissionMarketMchntPath = SpringContextUtil.getBean(RedpProperties.class).getBaseFilePath();

    @RequiresPermissions("银行对收银员营销活动管理:新增")
    @RequestMapping(value = "/toAdd", method = {RequestMethod.POST, RequestMethod.GET})
    public String toAdd() {
        // 获取当前登录用户信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        UpmpSysParam upmpSysParam = upmpSysParamService.findByPrimaryKey("marketOrgSelectedFlag", user.getInstId(), null);
        String marketOrgSelectedFlag = null;
        if (Common.isNotBlank(upmpSysParam)) {
            marketOrgSelectedFlag = upmpSysParam.getPrimaryValue();
        }
        return marketOrgSelectedFlag;
    }

    //    @RequiresPermissions(value = {"营销活动审核:详情","银行对收银员营销活动管理:详情","银行对收银员营销活动发布:详情"},logical = Logical.OR)
    @GetMapping("/toDetails")
    public Map<String, Object> toDetails(HttpServletRequest request) throws RedpException {
        Map<String, Object> result = new HashMap<>();
        QueryCashierCashbackMcDetailInfoRequest param = new QueryCashierCashbackMcDetailInfoRequest();
        //-- 0-银行人员(录入\审核\发布)
        param.setQueryType("0");
        //-- 00-银行录入
        param.setQueryRole("02");
        param.setMcNo(request.getParameter("mcNo"));
        Result<QueryCashierCashbackMcDetailInfoResponse> response = cashierService.getCashierMCDetail(param);
        if (!response.isSuccess()) {
            throw new RedpException("营销活动数据查询失败");
        }
        QueryCashierCashbackMcDetailInfoResponse resultData = response.getResult();

        // 时间格式转换
        CashierCashbackMcInfoBean mcInfoObj = resultData.getMcInfoObj();
        Date start = DateUtils.parseDate(mcInfoObj.getMcStartDate(), DateUtils.FORMAT_YYYYMMDD);
        Date end = DateUtils.parseDate(mcInfoObj.getMcEndDate(), DateUtils.FORMAT_YYYYMMDD);
        mcInfoObj.setMcStartDate(DateUtils.formatDate(start, DateUtils.DEFAULT_DATE_FORMAT));
        mcInfoObj.setMcEndDate(DateUtils.formatDate(end, DateUtils.DEFAULT_DATE_FORMAT));
        // TODO  商户反显，目前老平台未应答这个数据，估计是数据量太大，后面可注释掉
        if(CollectionUtils.isEmpty(resultData.getMchntInfoList())){
            resultData.setMchntInfoList(new ArrayList<>());
        }
        List<McMchntInfoBean> mchntCircleList = customerMarketService.getMchntCircleList(request.getParameter("mcNo"), "-1", "-1");
        if (!CollectionUtils.isEmpty(mchntCircleList)) {
            resultData.getMchntInfoList().addAll(mchntCircleList);
        }
        QueryMcMerUserListRequest reqDto = new QueryMcMerUserListRequest();
        reqDto.setMcNo(request.getParameter("mcNo"));
        reqDto.setQueryType("0");
        reqDto.setQueryRole("00");
        IPage<McMchntInfoBean> mchntList = customerMarketService.getMchntList(reqDto, "-1", "-1");
        if (!CollectionUtils.isEmpty(mchntList.getRecords())) {
            resultData.getMchntInfoList().addAll(mchntList.getRecords());
        }
        //
//        resultData.setMchntInfoList(customerMarketService.getMchntCircleList(request.getParameter("mcNo"), "-1", "-1"));
        result.put("mcNo", request.getParameter("mcNo"));
        result.put("auditRefuseReason", resultData.getMcInfoObj().getAuditRefuseReason());
        result.put("publishRefuseReason", resultData.getMcInfoObj().getPublishRefuseReason());
        result.put("datailData", JSONObject.toJSONString(resultData, SerializerFeature.WriteMapNullValue));
        result.put("circleList", customerMarketService.getMchntCircleList(request.getParameter("mcNo"), "-1", "-1"));

        return result;
    }

    //    @RequiresPermissions("银行对收银员营销活动管理:修改")
    @RequestMapping(value = "/toEdit", method = RequestMethod.GET)
    public Map<String, Object> toEdit(HttpServletRequest request) throws RedpException {
        Map<String, Object> result = new HashMap<>();
        QueryCashierCashbackMcDetailInfoRequest param = new QueryCashierCashbackMcDetailInfoRequest();
        //-- 0-银行人员(录入\审核\发布)
        param.setQueryType("0");
        //-- 00-银行录入
        param.setQueryRole("00");
        param.setMcNo(request.getParameter("mcNo"));
        Result<QueryCashierCashbackMcDetailInfoResponse> response = cashierService.getCashierMCDetail(param);
        if (!response.isSuccess()) {
            throw new RedpException("营销活动数据查询失败");
        }
        QueryCashierCashbackMcDetailInfoResponse resultData = response.getResult();

        // 时间格式转换
        CashierCashbackMcInfoBean mcInfoObj = resultData.getMcInfoObj();
        Date start = DateUtils.parseDate(mcInfoObj.getMcStartDate(), DateUtils.FORMAT_YYYYMMDD);
        Date end = DateUtils.parseDate(mcInfoObj.getMcEndDate(), DateUtils.FORMAT_YYYYMMDD);
        mcInfoObj.setMcStartDate(DateUtils.formatDate(start, DateUtils.DEFAULT_DATE_FORMAT));
        mcInfoObj.setMcEndDate(DateUtils.formatDate(end, DateUtils.DEFAULT_DATE_FORMAT));
        //
        String mcNo = request.getParameter("mcNo");
        result.put("mcNo", mcNo);

        // TODO  商户反显，目前老平台未应答这个数据，估计是数据量太大，后面可注释掉
        if(CollectionUtils.isEmpty(resultData.getMchntInfoList())){
            resultData.setMchntInfoList(new ArrayList<>());
        }
        List<McMchntInfoBean> mchntCircleList = customerMarketService.getMchntCircleList(request.getParameter("mcNo"), "-1", "-1");
        if (!CollectionUtils.isEmpty(mchntCircleList)) {
            resultData.getMchntInfoList().addAll(mchntCircleList);
        }
        QueryMcMerUserListRequest reqDto = new QueryMcMerUserListRequest();
        reqDto.setMcNo(request.getParameter("mcNo"));
        reqDto.setQueryType("0");
        reqDto.setQueryRole("00");
        IPage<McMchntInfoBean> mchntList = customerMarketService.getMchntList(reqDto, "-1", "-1");
        if (!CollectionUtils.isEmpty(mchntList.getRecords())) {
            resultData.getMchntInfoList().addAll(mchntList.getRecords());
        }
//        resultData.setMchntInfoList(customerMarketService.getMchntCircleList(mcNo, "-1", "-1"));
        result.put("datailData", JSONObject.toJSONString(resultData, SerializerFeature.WriteMapNullValue));
        return result;
    }

    /**
     * 删除
     *
     * @param request
     * @return
     */
//    @RequiresPermissions("银行对收银员营销活动管理:删除")
    @PostMapping(value = "/deleteMcData")
    public OperationResult deleteMcData(HttpServletRequest request) {
        Result<ManageCashierCashbackMcResponse> result = new Result<>();
        try {
            ManageCashierCashbackMcRequest param = new ManageCashierCashbackMcRequest();
            param.setQueryType("0");  //-- 0-银行人员(录入\审核\发布)
            param.setQueryRole("00");//-- 00-银行录入
            param.setMcNo(request.getParameter("mcNo"));
            param.setOprType("0"); //---  0-删除
            result = cashierService.handleCashierAgentMarket(param);

            if (null == result || null == result.getResult()) {
                log.error("删除营销活动时系统异常接口调用失败:result=[{}]", JSON.toJSONString(result));
                return OperationResult.buildFailureResult("删除营销活动时系统异常接口调用失败");
            }

            if (!BusinessContainer.BSPS_SUCCESS.equals(result.getResult().getRespCode())) {
                log.error("删除营销活动失败:code=[{}],msg=[{}]", result.getResult().getRespCode(), result.getResult().getRespDesc());
                return OperationResult.buildFailureResult("删除营销活动失败:" + result.getResult().getRespDesc());
            }

        } catch (Exception e) {
            log.error("删除营销活动时系统异常:[{}]", e);
            return OperationResult.buildFailureResult("删除营销活动时系统异常");
        }
        return OperationResult.buildSuccessResult("删除成功");
    }

    @RequestMapping(value = "/getOrgList", method = RequestMethod.GET)
    public List<UpmpOrgTreeInfo> getOrgList() throws RedpException {
        List<UpmpOrgTreeInfo> allOrgForTree;
        try {
            // 获取当前登录用户信息
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            allOrgForTree = organizationService.getAllOrgForTree(user.getOrgCode(), user.getInstId(), Lists.newArrayList());
        } catch (Exception e) {
            log.error("获取机构信息时系统异常:[{}]", e);
            throw new RedpException("获取机构信息时系统异常");
        }

        return allOrgForTree;
    }

    /**
     * 生成 Excel导入模板
     */
//    @CrossOrigin
    @PostMapping("getExcel")
    public void getExcel(HttpServletRequest request, HttpServletResponse response) {
        String fileName = "mchntNoBatchImportTemplate.xls";

        String filePath = getClass().getResource("/template/mchntNoBatchImportTemplate.xls").getPath();
        File file = new File(filePath);
        if (file == null) {
            return;
        }
        if (!file.exists()) {
            return;
        }
        OutputStream out = null;
        try {
            response.reset();
            response.setContentType("application/octet-stream; charset=utf-8");
            //兼容IE、火狐
            String header = request.getHeader("User-Agent");
            if(header.toLowerCase().contains("firefox")){
                BASE64Encoder base64Encoder = new BASE64Encoder();
                response.setHeader("Content-Disposition", "attachment; filename==?UTF-8?B?"+(new String(base64Encoder.encode(fileName.getBytes("UTF-8"))))+"?=" );
            }else {
                response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            }
            response.setHeader("Access-control-Allow-Origin", request.getHeader("Origin"));
            out = response.getOutputStream();
            out.write(FileUtils.readFileToByteArray(file));
            out.flush();
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
        }
    }

    //    @RequiresPermissions("营销管理:银行对收银员营销活动管理")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public OperationResult getDataFromExcel(@RequestParam(value = "excelFile", required = false) MultipartFile excelFile, HttpServletRequest request) {
        // 获取当前登录用户信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String originalFilename = excelFile.getOriginalFilename();
        if (!originalFilename.endsWith(".xls") && !originalFilename.endsWith(".xlsx")) {
            log.error("文件不是excel类型");
            return OperationResult.buildFailureResult("文件不是excel类型");
        }

        String date = DateUtils.formatDate(new Date(), DateUtils.FORMAT_YYYYMMDD);
        File filePath = new File(commissionMarketMchntPath + user.getInstId() + File.separator + date);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        String suff = originalFilename.substring(originalFilename.lastIndexOf(point));
        String fileName = DateUtils.formatDate(new Date(), DateUtils.FULL_SEQ_FORMAT) + suff;
        String fileRealPath = filePath + File.separator + fileName;
        try (InputStream in = excelFile.getInputStream(); OutputStream out = new FileOutputStream(filePath + File.separator + fileName)) {
            IOUtils.copy(in, out);
        } catch (Exception e) {
            log.error("上传文件 " + originalFilename + " 时系统异常:[{}]", e);
            return OperationResult.buildFailureResult("文件上传失败");
        }

        return OperationResult.buildSuccessResult(fileRealPath);
    }

    /**
     * 获取商户列表
     *
     * @param
     * @return
     */
//    @RequiresPermissions("营销管理:银行对收银员营销活动管理")
    @PostMapping(value = "/getMcList")
    public OperationResult getMcList(@RequestBody McCircletListQueryReqVO request) {
        MchntInfoListQueryRequest param = new MchntInfoListQueryRequest();
        // 可成功添加的列表
        List<McMchntInfoBean> mchntInfoList = new ArrayList<>();
        // 存在错误的列表
        List<McMchntInfoBean> errorList = new ArrayList<>();
        // 特殊费率商户的列表
        List<McMchntInfoBean> feeMchntList = new ArrayList<>();
        // 机构不符的列表
        List<McMchntInfoBean> orgMchntList = new ArrayList<>();

        try {
            // 获取当前登录用户信息
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            String data1 = request.getData();
            String[] split = data1.split(",");
            List<String> strings = Arrays.asList(split);

            // 页面选中的机构列表
            List<McOrgInfoBean> orgInfoList = request.getSelectedOrgInfoList();
            if (ObjectUtils.isEmpty(orgInfoList)) {
                return OperationResult.buildFailureResult("已选择的机构上送有误，请联系管理员");
            }
            Map<String, Boolean> selectedOrgMap = new HashMap<>();
            for (McOrgInfoBean mcOrgInfoBean : orgInfoList) {
                selectedOrgMap.put(mcOrgInfoBean.getOrgId(), true);
            }

            strings.forEach((e) -> {
                param.setMchntNo(e);
                Map<String, Object> maps = cashierService.queryMcNoList(user, param, bompMchntQueryService, genMerOrder(user));
                if (null != maps.get("results")) {
                    List resultList = (List) maps.get("results");
                    Map mcMap = (Map) resultList.get(0);
                    McMchntInfoBean mchntInfo1 = new McMchntInfoBean();
                    mchntInfo1.setMchntNo((String) mcMap.get("id"));
                    mchntInfo1.setMchntName((String) mcMap.get("name"));
                    mchntInfo1.setMchntType("0");//----0-商户 1-商圈

                    Boolean isFeeMchntFlag = marketService.checkFeeMchnt(user, e, bompMchntQueryService, genMerOrder(user));
                    String orgId = (String) mcMap.get("orgId");
                    if (!selectedOrgMap.containsKey(orgId)) {
                        // 判断商户的机构与选择的机构是否一致
                        orgMchntList.add(mchntInfo1);
                    } else if (isFeeMchntFlag) {
                        // 判断商户是否特殊费率
                        feeMchntList.add(mchntInfo1);
                    } else {
                        // 可成功添加
                        mchntInfoList.add(mchntInfo1);
                    }
                } else {
                    McMchntInfoBean mchntInfo1 = new McMchntInfoBean();
                    mchntInfo1.setMchntNo(e);
                    mchntInfo1.setMchntType("0");//----0-商户 1-商圈
                    errorList.add(mchntInfo1);
                }
            });
        } catch (Exception e) {
            log.error("获取商户信息时系统异常:[{}]", e);
            return OperationResult.buildFailureResult("获取商户信息时系统异常");
        }
        Map<String, List<McMchntInfoBean>> resultMap = new HashMap<>();
        resultMap.put("successData", mchntInfoList);
        resultMap.put("errorData", errorList);
        resultMap.put("feeMchntData", feeMchntList);
        resultMap.put("orgMchntData", orgMchntList);
        return OperationResult.buildSuccessResult("查询成功", resultMap);
    }

    /**
     * 获取商圈列表
     *
     * @param
     * @return
     */
//    @RequiresPermissions("营销管理:银行对收银员营销活动管理")
    @PostMapping(value = "/getMcCircletList")
    public OperationResult getMcCircletList(@RequestBody McCircletListQueryReqVO request) {
        MchntAreaListQueryRequest param = new MchntAreaListQueryRequest();
        MchntInfoListQueryRequest mchntInfoParam = new MchntInfoListQueryRequest();
        // 可成功添加的列表
        List<McMchntInfoBean> mchntInfoList = new ArrayList<>();
        // 存在错误的列表
        List<McMchntInfoBean> errorList = new ArrayList<>();
        // 特殊费率商户的列表
        List<McMchntInfoBean> feeMchntList = new ArrayList<>();
        // 机构不符的列表
        List<McMchntInfoBean> orgMchntList = new ArrayList<>();
        try {
            // 获取当前登录用户信息
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
//            String data1 = request.getParameter("data");
            String[] split = request.getData().split(",");
            List<String> strings = Arrays.asList(split);

            // 页面选中的机构列表
//            String orgInfoJson = StringEscapeUtils.unescapeHtml4(request.getParameter("selectedOrgInfoList"));
            if (ObjectUtils.isEmpty(request.getSelectedOrgInfoList())) {
                return OperationResult.buildFailureResult("已选择的机构上送有误，请联系管理员");
            }
//            List<McOrgInfoBean> orgInfoList = JSONArray.parseArray(orgInfoJson, McOrgInfoBean.class);
            Map<String, Boolean> selectedOrgMap = new HashMap<>();
            for (McOrgInfoBean mcOrgInfoBean : request.getSelectedOrgInfoList()) {
                selectedOrgMap.put(mcOrgInfoBean.getOrgId(), true);
            }

            strings.forEach((e) -> {
                param.setMchntArea(e);
                Map<String, Object> maps = cashierService.queryMchntAreaList(user, param, bompMchntQueryService, genMerOrder(user));
                if (null != maps.get("results")) {
                    List resultList = (List) maps.get("results");
                    Map mcMap = (Map) resultList.get(0);
                    McMchntInfoBean mchntInfo1 = new McMchntInfoBean();
                    mchntInfo1.setMchntNo((String) mcMap.get("id"));
                    mchntInfo1.setMchntName((String) mcMap.get("name"));
                    mchntInfo1.setMchntType("1");//----0-商户 1-商圈

                    String orgId = (String) mcMap.get("orgId");
                    if (!selectedOrgMap.containsKey(orgId)) {
                        // 判断商户的机构与选择的机构是否一致
                        orgMchntList.add(mchntInfo1);
                    } else {
                        // 根据商圈编号查询商户列表
                        Set<String> stringSet = new HashSet<>();
                        mchntInfoParam.setMchntArea(e);
                        Map<String, Object> mchntMaps = marketService.queryMcNoList(user, mchntInfoParam, genMerOrder(user));
                        if (null != mchntMaps.get("results")) {
                            List mchntList = (List) mchntMaps.get("results");
                            for (Object obj : mchntList) {
                                Map mchntMap = (Map) obj;
                                String mchntNo = (String) mchntMap.get("id");
                                // 判断商户是否特殊费率
                                Boolean isFeeMchntFlag = marketService.checkFeeMchnt(user, mchntNo, bompMchntQueryService, genMerOrder(user));
                                if (isFeeMchntFlag) {
                                    if (!stringSet.contains(e)) {
                                        feeMchntList.add(mchntInfo1);
                                    }
                                } else {
                                    // 可成功添加
                                    if (!stringSet.contains(e)) {
                                        mchntInfoList.add(mchntInfo1);
                                    }
                                }
                                stringSet.add(e);
                            }
                        } else {
                            // 可成功添加
                            mchntInfoList.add(mchntInfo1);
                        }
                    }
                } else {
                    McMchntInfoBean mchntInfo1 = new McMchntInfoBean();
                    mchntInfo1.setMchntNo(e);
                    mchntInfo1.setMchntType("1");//----0-商户 1-商圈
                    errorList.add(mchntInfo1);
                }
            });
        } catch (Exception e) {
            log.error("获取商户信息时系统异常:[{}]", e);
            return OperationResult.buildFailureResult("获取商户信息时系统异常");
        }
        Map<String, List<McMchntInfoBean>> resultMap = new HashMap<>();
        resultMap.put("successData", mchntInfoList);
        resultMap.put("errorData", errorList);
        resultMap.put("feeMchntData", feeMchntList);
        resultMap.put("orgMchntData", orgMchntList);
        return OperationResult.buildSuccessResult("查询成功", resultMap);
    }


    /**
     * 查询首页  list
     *
     * @param request
     * @return
     */
//    @RequiresPermissions("营销管理:银行对收银员营销活动管理")
    @GetMapping("/getMcInfo")
    public IPage<CashierCashbackMcListInfoBean> McInfo(QueryRequest request, CashierCashbackMcVO vo) throws RedpException {

        IPage<CashierCashbackMcListInfoBean> cashierMCList = null;
        try {
            QueryCashierCashbackMcListInfoRequest queryParam = new QueryCashierCashbackMcListInfoRequest();
            queryParam.setQueryType("0");
            queryParam.setQueryRole("00");
            queryParam.setMcType("40");
            //------------------------------------------------------
            if (StringUtils.isNotEmpty(vo.getStartTime())) {
                queryParam.setStartTime(vo.getStartTime());
            }
            if (StringUtils.isNotEmpty(vo.getEndTime())) {
                queryParam.setEndTime(vo.getEndTime());
            }
            queryParam.setMcNo(vo.getMcNo());
            queryParam.setMcStatus(vo.getMcStatus());
            queryParam.setMchntNo(vo.getMchntNo());
            queryParam.setMchntName(vo.getMchntName());
            queryParam.setCashbackMethod(vo.getCashbackMethod());
            cashierMCList = cashierService.getCashierMCList(queryParam, request);
            if (cashierMCList != null && cashierMCList.getSize() > 0) {
                List<CashierCashbackMcListInfoBean> list = cashierMCList.getRecords();
                for (CashierCashbackMcListInfoBean bean : list) {
                    String userId = bean.getOprId();
                    UpmpUserInfo user = userService.findById(userId);
                    if (Common.isNotBlank(user)) {
                        bean.setOprId(user.getUserName());
                    }
                }
            }
        } catch (Exception e) {
            log.error("获取营销活动信息时系统异常:[{}]", e);
            throw new RedpException("获取营销活动信息时系统异常:" + e.getMessage());
        }

        return cashierMCList;

    }

    //----------------------------------------查询打款明细List
//    @RequiresPermissions("营销管理:银行对收银员营销活动管理")
    @ResponseBody
    @RequestMapping(value = "/getPalyList", method = RequestMethod.GET)
    public IPage getPalyList(QueryRequest request, CashierCashbackToCashierDetailVO vo) throws RedpException {
        IPage<CashierCashbackToCashierDetailInfoBean> result;
        try {
            QueryCashbackToCashierDetailRequest param = new QueryCashbackToCashierDetailRequest();
            param.setQueryType("0");
            param.setQueryRole("00");
            //------------------------------------------------------
            param.setMcNo(vo.getMcNo());
            param.setAcctNo(vo.getAcctNo());
            param.setMchntNo(vo.getMchntNo());
            if (StringUtils.isNotBlank(vo.getCashbackDate())) {
                Date cashbackDate = DateUtils.parseDate(vo.getCashbackDate(), DateUtils.DEFAULT_DATE_FORMAT);
                param.setCashbackDate(DateUtils.formatDate(cashbackDate, DateUtils.FORMAT_YYYYMMDD));
            }
            param.setCashbackStatus(vo.getCashbackStatus());
            param.setMcType("40");//40-收银员返现活动
            result = cashierService.getCashierMCDetailList(param, request);


        } catch (Exception e) {
            log.error("查询打款明细时系统异常:[{}]", e);
            throw new RedpException("查询打款明细时系统异常");
        }
        return result;

    }

    //创建
//    @RequiresPermissions(value = {"银行对收银员营销活动管理:新增","银行对收银员营销活动管理:修改"},logical = Logical.OR)
    @PostMapping(value = "/createCampaign")
    public OperationResult createCampaign(@RequestBody CampaignSaveReqVO request) {
        Result<EditCashierCashbackMcDetailResponse> result = new Result<>();
        EditCashierCashbackMcDetailRequest param = new EditCashierCashbackMcDetailRequest();
        try {

            param.setOprType("1");//  0-保存1-提交审批2-修改草稿(临时表)
            param.setMrctFilePath(request.getMrctFilePath());
            CashierCashbackMcInfoBean mcInfoBean = getCashierInfoBean(request);
            // 获取当前登录用户信息
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            mcInfoBean.setInstId(user.getInstId());
            mcInfoBean.setOprId(user.getId());//创建人
            mcInfoBean.setCreateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
            mcInfoBean.setAuditStatus(request.getAuditStatus());
            mcInfoBean.setMcStatus("0");//0-草稿
            mcInfoBean.setMcType("40");//40-收银员返现活动
            String auditStatus = request.getAuditStatus();
            if ("01".equals(auditStatus)) {//01新增审批流程
                mcInfoBean.setOprId(user.getId());//创建人
                mcInfoBean.setCreateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
            } else if ("41".equals(auditStatus)) {//41修改审批流程
                mcInfoBean.setMcNo(request.getMcNo());
                mcInfoBean.setOprId(request.getOprId());//创建人
                mcInfoBean.setCreateTime(request.getCreateTime());
                mcInfoBean.setUpdateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
                mcInfoBean.setLastOprId(user.getId());
            } else {
                log.error("审核状态不匹配:param=[{}]", JSON.toJSONString(param));
                return OperationResult.buildFailureResult("创建营销活动失败:审核状态不匹配");

            }

            param.setMcInfoObj(mcInfoBean);

            setListParam(param, request);
            result = cashierService.EditCashierAgentMarket(param);
            if (null == result || null == result.getResult()) {
                log.error("创建营销活动时系统异常接口调用失败:result=[{}]", JSON.toJSONString(result));
                return OperationResult.buildFailureResult("创建营销活动时系统异常接口调用失败");
            }

            if (!BusinessContainer.BSPS_SUCCESS.equals(result.getResult().getRespCode())) {
                log.error("创建营销活动失败:code=[{}],msg=[{}]", result.getResult().getRespCode(), result.getResult().getRespDesc());
                return OperationResult.buildFailureResult("创建营销活动失败:" + result.getResult().getRespDesc());
            }

        } catch (Exception e) {
            log.error("创建营销活动时系统异常:[{}]", e);
            return OperationResult.buildFailureResult("创建营销活动时系统异常");
        }


        return OperationResult.buildSuccessResult("创建营销活动成功请等待审核");
    }

    private void setListParam(EditCashierCashbackMcDetailRequest param, CampaignSaveReqVO request) {
        //----------产品信息
        List<String> upLineProduces = request.getUpLineProduce();
        ArrayList<McProductInfoBean> productInfoList = new ArrayList<>();
        for (String code : upLineProduces) {
            McProductInfoBean productInfoBean = new McProductInfoBean();
            productInfoBean.setBizProdCode(code);
            productInfoList.add(productInfoBean);
        }
        param.setProductInfoList(productInfoList);

        //---------商户  商圈
        List<McMchntInfoBean> mcMchntList = new ArrayList<>();
        mcMchntList.addAll(request.getMerchantInfo());
        mcMchntList.addAll(request.getMerchantCircleInfo());
        param.setMchntInfoList(mcMchntList);

        //---------营销方式
        param.setRuleInfoList(request.getRuleInfo());

        //-------orgInfoList  机构信息
        param.setOrgInfoList(request.getOrgInfo());
    }

    /**
     * 保存
     *
     * @param request
     * @return
     */
//    @RequiresPermissions("银行对收银员营销活动管理:新增")
    @PostMapping(value = "/saveCampaign")
    public OperationResult saveCampaign(@RequestBody CampaignSaveReqVO request) {
        Result<EditCashierCashbackMcDetailResponse> result = new Result<>();
        EditCashierCashbackMcDetailRequest param = new EditCashierCashbackMcDetailRequest();
        try {

            param.setOprType("0");//  0-保存1-提交审批2-修改草稿(临时表)

            CashierCashbackMcInfoBean mcInfoBean = getCashierInfoBean(request);
            // 获取当前登录用户信息
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            mcInfoBean.setInstId(user.getInstId());
            mcInfoBean.setOprId(user.getId());//创建人
            mcInfoBean.setCreateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
            mcInfoBean.setAuditStatus("00");//00-待提交审批,
            mcInfoBean.setMcStatus("0");//0-草稿
            mcInfoBean.setMcType("40");//40-收银员返现活动
            param.setMcInfoObj(mcInfoBean);
            setListParam(param, request);
            param.setMrctFilePath(request.getMrctFilePath());
            result = cashierService.EditCashierAgentMarket(param);
            if (null == result || null == result.getResult()) {
                log.error("保存营销活动时系统异常接口调用失败:result=[{}]", JSON.toJSONString(result));
                return OperationResult.buildFailureResult("保存营销活动时系统异常接口调用失败");
            }

            if (!BusinessContainer.BSPS_SUCCESS.equals(result.getResult().getRespCode())) {
                log.error("保存营销活动失败:code=[{}],msg=[{}]", result.getResult().getRespCode(), result.getResult().getRespDesc());
                return OperationResult.buildFailureResult("保存营销活动失败:" + result.getResult().getRespDesc());
            }

        } catch (Exception e) {
            log.error("营销活动修改时系统异常:[{}]", e);
            return OperationResult.buildFailureResult("保存营销活动时系统异常");
        }


        return OperationResult.buildSuccessResult("保存营销活动成功");
    }

    /**
     * 修改
     *
     * @param request
     * @return
     */
//    @RequiresPermissions("银行对收银员营销活动管理:修改")
    @PostMapping("/editCampaign")
    public OperationResult editCampaign(@RequestBody CampaignSaveReqVO request) {
        Result<EditCashierCashbackMcDetailResponse> result = new Result<>();
        EditCashierCashbackMcDetailRequest param = new EditCashierCashbackMcDetailRequest();
        try {
            // 保存草稿操作使用：0-保存
            param.setOprType("0");//  0-保存1-提交审批2-修改草稿

            CashierCashbackMcInfoBean mcInfoBean = getCashierInfoBean(request);
            // 获取当前登录用户信息
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            mcInfoBean.setMcNo(request.getMcNo());
            mcInfoBean.setMcType(request.getMcType());
            mcInfoBean.setInstId(user.getInstId());
            mcInfoBean.setAuditStatus("00");//00-待提交审批,
            mcInfoBean.setMcStatus("0");//0-草稿
            mcInfoBean.setOprId(request.getOprId());//创建人
            mcInfoBean.setCreateTime(request.getCreateTime());
            mcInfoBean.setUpdateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
            mcInfoBean.setLastOprId(user.getId());
            param.setMcInfoObj(mcInfoBean);
            param.setMrctFilePath(request.getMrctFilePath());
            setListParam(param, request);
            result = cashierService.EditCashierAgentMarket(param);
            if (null == result || null == result.getResult()) {
                log.error("营销活动修改时系统异常接口调用失败:result=[{}]", JSON.toJSONString(result));
                return OperationResult.buildFailureResult("营销活动修改时系统异常接口调用失败");
            }

            if (!BusinessContainer.BSPS_SUCCESS.equals(result.getResult().getRespCode())) {
                log.error("营销活动修改失败:code=[{}],msg=[{}]", result.getResult().getRespCode(), result.getResult().getRespDesc());
                return OperationResult.buildFailureResult("营销活动修改失败:" + result.getResult().getRespDesc());
            }

        } catch (Exception e) {
            log.error("营销活动修改时系统异常:[{}]", e);
            return OperationResult.buildFailureResult("营销活动修改时系统异常");
        }


        return OperationResult.buildSuccessResult("营销活动修改成功");
    }

    private CashierCashbackMcInfoBean getCashierInfoBean(CampaignSaveReqVO request) throws RedpException {
        CashierCashbackMcInfoBean infoBean = new CashierCashbackMcInfoBean();
        infoBean.setMcNo(request.getMcNo());
        infoBean.setMcName(request.getMcName());
        infoBean.setMcType(request.getMcType());
        infoBean.setMcStatus(request.getMcStatus());
        Date mcStartDate = DateUtils.parseDate(request.getMcStartDate(), DateUtils.DEFAULT_DATE_FORMAT);
        infoBean.setMcStartDate(DateUtils.formatDate(mcStartDate, DateUtils.FORMAT_YYYYMMDD));
        String mcEndDateStr = request.getMcEndDate();
        if (StringUtils.isNotBlank(mcEndDateStr)) {
            Date mcEndDate = DateUtils.parseDate(mcEndDateStr, DateUtils.DEFAULT_DATE_FORMAT);
            infoBean.setMcEndDate(DateUtils.formatDate(mcEndDate, DateUtils.FORMAT_YYYYMMDD));
        }

        infoBean.setDiscountTransferMode(request.getDiscountTransferMode());//退出待定
        String discountTransferMode = request.getDiscountTransferMode();
        if ("0".equals(discountTransferMode)) {
            infoBean.setBudget(request.getBudget());
        } else if ("1".equals(discountTransferMode)) {
            infoBean.setPointRuleData(request.getPointRuleData());
        } else {
            log.error("优惠打款模式不匹配");
            throw new RedpException("优惠打款模式不匹配");
        }

        infoBean.setCriteriaFlag(request.getCriteriaFlag());
        infoBean.setCriteriaLimit(request.getCriteriaLimit());
        infoBean.setStatPeriod(request.getStatPeriod());

        String criteriaAmount = request.getCriteriaAmount();
        if (StringUtils.isBlank(criteriaAmount)) {
            infoBean.setCriteriaAmount("0");
        } else {
            infoBean.setCriteriaAmount(criteriaAmount);
        }
        String criteriaQuantity = request.getCriteriaQuantity();
        if (StringUtils.isBlank(criteriaQuantity)) {
            infoBean.setCriteriaQuantity("0");
        } else {
            infoBean.setCriteriaQuantity(criteriaQuantity);
        }


        infoBean.setTerminationFlagPerson(request.getTerminationFlagPerson());
        String quantityLimitPerson = request.getQuantityLimitPerson();
        if (StringUtils.isBlank(quantityLimitPerson)) {
            infoBean.setQuantityLimitPerson("0");
        } else {
            infoBean.setQuantityLimitPerson(quantityLimitPerson);
        }
        String amountLimitPerson = request.getAmountLimitPerson();
        if (StringUtils.isBlank(amountLimitPerson)) {
            infoBean.setAmountLimitPerson("0");
        } else {
            infoBean.setAmountLimitPerson(amountLimitPerson);
        }
        String cashbackLimitPerson = request.getCashbackLimitPerson();
        if (StringUtils.isBlank(cashbackLimitPerson)) {
            infoBean.setCashbackLimitPerson("0");
        } else {
            infoBean.setCashbackLimitPerson(cashbackLimitPerson);
        }

        infoBean.setTerminationFlagMc(request.getTerminationFlagMc());
        String quantityLimitMc = request.getQuantityLimitMc();
        if (StringUtils.isBlank(quantityLimitMc)) {
            infoBean.setQuantityLimitMc("0");
        } else {
            infoBean.setQuantityLimitMc(quantityLimitMc);
        }

        String amountLimitMc = request.getAmountLimitMc();
        if (StringUtils.isBlank(amountLimitMc)) {
            infoBean.setAmountLimitMc("0");
        } else {
            infoBean.setAmountLimitMc(amountLimitMc);
        }

        String cashbackLimitMc = request.getCashbackLimitMc();
        if (StringUtils.isBlank(cashbackLimitPerson)) {
            infoBean.setCashbackLimitMc("0");
        } else {
            infoBean.setCashbackLimitMc(cashbackLimitMc);
        }


        infoBean.setCashbackMethod(request.getCashbackMethod());

        return infoBean;

    }

    /**
     * 获取发布账户信息
     */
    @ResponseBody
    @RequestMapping(value = "/getMcAccountInfo", method = RequestMethod.GET)
    public OperationResult McAccountInfo() {
        log.info("法人机构营销活动账号");
        Result<QueryInstitutionMcAccountInfoResponse> mcAccountInfo = null;
        try {
            mcAccountInfo = cashierService.getMcAccountInfo();
        } catch (Exception e) {
            return OperationResult.buildFailureResult("获取法人机构营销活动账号时系统异常:" + e.getMessage());
        }
        return OperationResult.buildSuccessResult(mcAccountInfo);
    }

    /**
     * 收银员返现积分规则
     *
     * @param
     * @return
     */

    @ResponseBody
    @RequestMapping(value = "/getBonusRuleList", method = RequestMethod.GET)
    public OperationResult getBonusRuleList() throws RedpException {
        log.info("获取收银员返现积分规则");
        Result<QueryCashierCashbackBonusRuleResponse> bonusRuleList = null;
        try {
            bonusRuleList = cashierService.getBonusRuleList();
        } catch (RedpException e) {
            return OperationResult.buildFailureResult("获取收银员返现积分规则时系统异常:" + e.getMessage());
        } catch (Exception e) {
            return OperationResult.buildFailureResult("获取收银员返现积分规则时系统异常");
        }
        return OperationResult.buildSuccessResult(bonusRuleList);
    }

    //----------审核---------------------------------------------------

    //    @RequiresPermissions("营销活动审核:审核")
    @RequestMapping(value = "/toCheck", method = RequestMethod.GET)
    public Map<String, Object> toCheck(HttpServletRequest request) throws RedpException {
        Map<String, Object> result = new HashMap<>();
        String auditStatus = request.getParameter("auditStatus");
        if (StringUtils.isBlank(auditStatus) || (!("01".equals(auditStatus)) && !("11".equals(auditStatus)) && !("21".equals(auditStatus)) && !("31".equals(auditStatus)) && !("41".equals(auditStatus)) && !("51".equals(auditStatus)))) {
            throw new RedpException("请求数据有误");
        }
        QueryCashierCashbackMcDetailInfoRequest param = new QueryCashierCashbackMcDetailInfoRequest();
        //-- 0-银行人员(录入\审核\发布)
        param.setQueryType("0");
        //-- 01-银行审核
        param.setQueryRole("01");
        param.setMcNo(request.getParameter("mcNo"));
        Result<QueryCashierCashbackMcDetailInfoResponse> response = cashierService.getCashierMCDetail(param);
        if (!response.isSuccess()) {
            throw new RedpException("营销活动数据查询失败");
        }
        QueryCashierCashbackMcDetailInfoResponse resultData = response.getResult();
        // 时间格式转换
        CashierCashbackMcInfoBean mcInfoObj = resultData.getMcInfoObj();
        Date start = DateUtils.parseDate(mcInfoObj.getMcStartDate(), DateUtils.FORMAT_YYYYMMDD);
        Date end = DateUtils.parseDate(mcInfoObj.getMcEndDate(), DateUtils.FORMAT_YYYYMMDD);
        mcInfoObj.setMcStartDate(DateUtils.formatDate(start, DateUtils.DEFAULT_DATE_FORMAT));
        mcInfoObj.setMcEndDate(DateUtils.formatDate(end, DateUtils.DEFAULT_DATE_FORMAT));
        // TODO  商户反显，目前老平台未应答这个数据，估计是数据量太大，后面可注释掉
        if(CollectionUtils.isEmpty(resultData.getMchntInfoList())){
            resultData.setMchntInfoList(new ArrayList<>());
        }
        List<McMchntInfoBean> mchntCircleList = customerMarketService.getMchntCircleList(request.getParameter("mcNo"), "-1", "-1");
        if (!CollectionUtils.isEmpty(mchntCircleList)) {
            resultData.getMchntInfoList().addAll(mchntCircleList);
        }
        QueryMcMerUserListRequest reqDto = new QueryMcMerUserListRequest();
        reqDto.setMcNo(request.getParameter("mcNo"));
        reqDto.setQueryType("0");
        reqDto.setQueryRole("00");
        IPage<McMchntInfoBean> mchntList = customerMarketService.getMchntList(reqDto, "-1", "-1");
        if (!CollectionUtils.isEmpty(mchntList.getRecords())) {
            resultData.getMchntInfoList().addAll(mchntList.getRecords());
        }
        //
//        resultData.setMchntInfoList(customerMarketService.getMchntCircleList(request.getParameter("mcNo"), "-1", "-1"));
        result.put("mcNo", request.getParameter("mcNo"));
        result.put("datailData", JSONObject.toJSONString(resultData, SerializerFeature.WriteMapNullValue));
        return result;
    }

    //审核
//    @RequiresPermissions("营销活动审核:审核")
    @ResponseBody
    @RequestMapping(value = "/checkCash", method = RequestMethod.POST)
    public OperationResult checkPass(HttpServletRequest request) {
        Result<ManageCashierCashbackMcResponse> result = new Result<>();
        ManageCashierCashbackMcRequest param = new ManageCashierCashbackMcRequest();
        try {
            param.setQueryType("0");
            param.setQueryRole("01");
            param.setMcNo(request.getParameter("mcNo"));
            param.setOprType(request.getParameter("oprType"));
            param.setMcNo(request.getParameter("mcNo"));
            param.setOprContent(request.getParameter("oprContent"));
            result = cashierService.handleCashierAgentMarket(param);
            if (null == result || null == result.getResult()) {
                log.error("审核营销活动时系统异常接口调用失败:result=[{}]", JSON.toJSONString(result));
                return OperationResult.buildFailureResult("审核营销活动时系统异常接口调用失败");
            }

            if (!BusinessContainer.BSPS_SUCCESS.equals(result.getResult().getRespCode())) {
                log.error("审核营销活动失败:code=[{}],msg=[{}]", result.getResult().getRespCode(), result.getResult().getRespDesc());
                return OperationResult.buildFailureResult("审核营销活动失败:" + result.getResult().getRespDesc());
            }

        } catch (Exception e) {
            log.error("审核营销活动时系统异常:[{}]", e);
            return OperationResult.buildFailureResult("审核营销活动时系统异常");
        }


        return OperationResult.buildSuccessResult("审核营销活动操作成功");
    }

    //---------发布----------------------------------------------------------

    //发布
//    @RequiresPermissions("银行对收银员营销活动发布:发布")
    @RequestMapping(value = "/toRelease", method = RequestMethod.GET)
    public Map<String, Object> toRelease(HttpServletRequest request) throws RedpException {
        Map<String, Object> result = new HashMap<>();
        QueryCashierCashbackMcDetailInfoRequest param = new QueryCashierCashbackMcDetailInfoRequest();
        // 获取当前登录用户信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        //-- 0-银行人员(录入\审核\发布)
        param.setQueryType("0");
        //-- 01-银行审核
        param.setQueryRole("02");
        param.setMcNo(request.getParameter("mcNo"));
        Result<QueryCashierCashbackMcDetailInfoResponse> response = cashierService.getCashierMCDetail(param);
        if (!response.isSuccess()) {
            throw new RedpException("营销活动数据查询失败");
        }
        QueryCashierCashbackMcDetailInfoResponse resultData = response.getResult();
        // 时间格式转换
        CashierCashbackMcInfoBean mcInfoObj = resultData.getMcInfoObj();
        Date start = DateUtils.parseDate(mcInfoObj.getMcStartDate(), DateUtils.FORMAT_YYYYMMDD);
        Date end = DateUtils.parseDate(mcInfoObj.getMcEndDate(), DateUtils.FORMAT_YYYYMMDD);
        mcInfoObj.setMcStartDate(DateUtils.formatDate(start, DateUtils.DEFAULT_DATE_FORMAT));
        mcInfoObj.setMcEndDate(DateUtils.formatDate(end, DateUtils.DEFAULT_DATE_FORMAT));

        //802行点选营销活动“发布”按钮后该活动直接发布，无须确认是否打款这一环节
        UpmpSysParam upmpSysParam = upmpSysParamService.findByPrimaryKey("skipPub", user.getInstId(), null);
        if (Common.isNotBlank(upmpSysParam)) {
            result.put("skipPub", upmpSysParam.getPrimaryValue());
        }
        // TODO  商户反显，目前老平台未应答这个数据，估计是数据量太大，后面可注释掉
        if(CollectionUtils.isEmpty(resultData.getMchntInfoList())){
            resultData.setMchntInfoList(new ArrayList<>());
        }
        List<McMchntInfoBean> mchntCircleList = customerMarketService.getMchntCircleList(request.getParameter("mcNo"), "-1", "-1");
        if (!CollectionUtils.isEmpty(mchntCircleList)) {
            resultData.getMchntInfoList().addAll(mchntCircleList);
        }
        QueryMcMerUserListRequest reqDto = new QueryMcMerUserListRequest();
        reqDto.setMcNo(request.getParameter("mcNo"));
        reqDto.setQueryType("0");
        reqDto.setQueryRole("00");
        IPage<McMchntInfoBean> mchntList = customerMarketService.getMchntList(reqDto, "-1", "-1");
        if (!CollectionUtils.isEmpty(mchntList.getRecords())) {
            resultData.getMchntInfoList().addAll(mchntList.getRecords());
        }
        //
//        resultData.setMchntInfoList(customerMarketService.getMchntCircleList(request.getParameter("mcNo"), "-1", "-1"));
        result.put("mcNo", request.getParameter("mcNo"));
        result.put("datailData", JSONObject.toJSONString(resultData, SerializerFeature.WriteMapNullValue));
        result.put("flag", "release");
        return result;
    }

    //终止
//    @RequiresPermissions("银行对收银员营销活动发布:终止")
    @RequestMapping(value = "/toShutdown", method = RequestMethod.GET)
    public Map<String, Object> toShutdown(HttpServletRequest request) throws RedpException {
        Map<String, Object> result = new HashMap<>();
        QueryCashierCashbackMcDetailInfoRequest param = new QueryCashierCashbackMcDetailInfoRequest();
        //-- 0-银行人员(录入\审核\发布)
        param.setQueryType("0");
        //-- 01-银行审核
        param.setQueryRole("02");
        param.setMcNo(request.getParameter("mcNo"));
        Result<QueryCashierCashbackMcDetailInfoResponse> response = cashierService.getCashierMCDetail(param);
        if (!response.isSuccess()) {
            throw new RedpException("营销活动数据查询失败");
        }
        QueryCashierCashbackMcDetailInfoResponse resultData = response.getResult();
        // 时间格式转换
        CashierCashbackMcInfoBean mcInfoObj = resultData.getMcInfoObj();
        Date start = DateUtils.parseDate(mcInfoObj.getMcStartDate(), DateUtils.FORMAT_YYYYMMDD);
        Date end = DateUtils.parseDate(mcInfoObj.getMcEndDate(), DateUtils.FORMAT_YYYYMMDD);
        mcInfoObj.setMcStartDate(DateUtils.formatDate(start, DateUtils.DEFAULT_DATE_FORMAT));
        mcInfoObj.setMcEndDate(DateUtils.formatDate(end, DateUtils.DEFAULT_DATE_FORMAT));
        //
        result.put("mcNo", request.getParameter("mcNo"));
        result.put("datailData", JSONObject.toJSONString(resultData, SerializerFeature.WriteMapNullValue));
        result.put("flag", "shutdown");
        return result;
    }

    //暂停
//    @RequiresPermissions("银行对收银员营销活动发布:暂停")
    @RequestMapping(value = "/toPause", method = RequestMethod.GET)
    public Map<String, Object> toPause(HttpServletRequest request) throws RedpException {
        Map<String, Object> result = new HashMap<>();
        QueryCashierCashbackMcDetailInfoRequest param = new QueryCashierCashbackMcDetailInfoRequest();
        //-- 0-银行人员(录入\审核\发布)
        param.setQueryType("0");
        //-- 01-银行审核
        param.setQueryRole("02");
        param.setMcNo(request.getParameter("mcNo"));
        Result<QueryCashierCashbackMcDetailInfoResponse> response = cashierService.getCashierMCDetail(param);
        if (!response.isSuccess()) {
            throw new RedpException("营销活动数据查询失败");
        }
        QueryCashierCashbackMcDetailInfoResponse resultData = response.getResult();
        // 时间格式转换
        CashierCashbackMcInfoBean mcInfoObj = resultData.getMcInfoObj();
        Date start = DateUtils.parseDate(mcInfoObj.getMcStartDate(), DateUtils.FORMAT_YYYYMMDD);
        Date end = DateUtils.parseDate(mcInfoObj.getMcEndDate(), DateUtils.FORMAT_YYYYMMDD);
        mcInfoObj.setMcStartDate(DateUtils.formatDate(start, DateUtils.DEFAULT_DATE_FORMAT));
        mcInfoObj.setMcEndDate(DateUtils.formatDate(end, DateUtils.DEFAULT_DATE_FORMAT));
        //
        result.put("mcNo", request.getParameter("mcNo"));
        result.put("datailData", JSONObject.toJSONString(resultData, SerializerFeature.WriteMapNullValue));
        result.put("flag", "pause");
        return result;
    }

    //启用
//    @RequiresPermissions("银行对收银员营销活动发布:启用")
    @RequestMapping(value = "/toResume", method = RequestMethod.GET)
    public Map<String, Object> toResume(HttpServletRequest request) throws RedpException {
        Map<String, Object> result = new HashMap<>();
        QueryCashierCashbackMcDetailInfoRequest param = new QueryCashierCashbackMcDetailInfoRequest();
        //-- 0-银行人员(录入\审核\发布)
        param.setQueryType("0");
        //-- 01-银行审核
        param.setQueryRole("02");
        param.setMcNo(request.getParameter("mcNo"));
        Result<QueryCashierCashbackMcDetailInfoResponse> response = cashierService.getCashierMCDetail(param);
        if (!response.isSuccess()) {
            throw new RedpException("营销活动数据查询失败");
        }
        QueryCashierCashbackMcDetailInfoResponse resultData = response.getResult();
        // 时间格式转换
        CashierCashbackMcInfoBean mcInfoObj = resultData.getMcInfoObj();
        Date start = DateUtils.parseDate(mcInfoObj.getMcStartDate(), DateUtils.FORMAT_YYYYMMDD);
        Date end = DateUtils.parseDate(mcInfoObj.getMcEndDate(), DateUtils.FORMAT_YYYYMMDD);
        mcInfoObj.setMcStartDate(DateUtils.formatDate(start, DateUtils.DEFAULT_DATE_FORMAT));
        mcInfoObj.setMcEndDate(DateUtils.formatDate(end, DateUtils.DEFAULT_DATE_FORMAT));
        //
        result.put("mcNo", request.getParameter("mcNo"));
        result.put("datailData", JSONObject.toJSONString(resultData, SerializerFeature.WriteMapNullValue));
        result.put("flag", "resume");
        return result;
    }

    //查询List
    //发布
//    @RequiresPermissions("营销管理:银行对收银员营销活动发布")
    @ResponseBody
    @RequestMapping(value = "/getpubList", method = RequestMethod.GET)
    public IPage<CashierCashbackMcListInfoBean> getpubList(QueryRequest request, CashierCashbackMcVO vo) throws RedpException {
        IPage<CashierCashbackMcListInfoBean> cashierMCList = null;
        try {
            QueryCashierCashbackMcListInfoRequest queryParam = new QueryCashierCashbackMcListInfoRequest();
            queryParam.setQueryType("0");
            queryParam.setQueryRole("02");
            //------------------------------------------------------
            if (StringUtils.isNotEmpty(vo.getStartTime())) {
                queryParam.setStartTime(vo.getStartTime());
            }
            if (StringUtils.isNotEmpty(vo.getEndTime())) {
                queryParam.setEndTime(vo.getEndTime());
            }
            queryParam.setMcNo(vo.getMcNo());
            queryParam.setMcStatus(vo.getMcStatus());
            queryParam.setMcType("40");
            queryParam.setCashbackMethod(vo.getCashbackMethod());
            cashierMCList = cashierService.getCashierMCList(queryParam, request);
            if (cashierMCList != null && cashierMCList.getSize() > 0) {
                List<CashierCashbackMcListInfoBean> list = cashierMCList.getRecords();
                for (CashierCashbackMcListInfoBean bean : list) {
                    String userId = bean.getOprId();
                    UpmpUserInfo user = userService.findById(userId);
                    if (Common.isNotBlank(user)) {
                        bean.setOprId(user.getUserName());
                    }
                }
            }
        } catch (RedpException e) {
            log.error("获取营销活动信息时系统异常:[{}]", e);
            throw new RedpException("获取营销活动信息时系统异常:" + e.getMessage());
        }

        return cashierMCList;
    }

    //发布
//    @RequiresPermissions("银行对收银员营销活动发布:发布")
    @ResponseBody
    @RequestMapping(value = "/releaseAgent", method = RequestMethod.POST)
    public OperationResult releaseAgent(HttpServletRequest request) {
        Result<PublishCashierCashbackMcResponse> result = new Result<>();
        PublishCashierCashbackMcRequest param = new PublishCashierCashbackMcRequest();
        String resMs = "";
        String skipPub = "";
        try {
            param.setQueryType("0");
            //  02-发布
            param.setQueryRole("02");
            param.setMcNo(request.getParameter("mcNo"));
            param.setOprType(request.getParameter("oprType"));
            param.setOprContent(request.getParameter("oprContent"));
            // 账户信息
            McBankAccountInfoBean accountInfoBean = new McBankAccountInfoBean();
            accountInfoBean.setPayAcctNo(request.getParameter("payAcctNo"));
            //accountInfoBean.setPayAcctName(request.getParameter("payAcctName"));
            accountInfoBean.setIdType(request.getParameter("idType"));
            accountInfoBean.setIdNo(request.getParameter("idNo"));
            accountInfoBean.setCellPhoneNumber(request.getParameter("cellPhoneNumber"));
            accountInfoBean.setPicCapcha(request.getParameter("picCapcha"));
            accountInfoBean.setSmsCapcha(request.getParameter("smsCapcha"));
            param.setAcctInfoObk(accountInfoBean);

            // 获取当前登录用户信息
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);

            UpmpSysParam upmpSysParam = upmpSysParamService.findByPrimaryKey("skipPub", user.getInstId(), null);
            if (Common.isNotBlank(upmpSysParam)) {
                skipPub = upmpSysParam.getPrimaryValue();
            }

            String oprType = request.getParameter("oprType");
            if ("0".equals(oprType)) {// 0-发布活动  1-退回修改
                resMs = "发布";
            } else if ("1".equals(oprType)) {
                resMs = "退回";
            } else {
                throw new RedpException("请求参数有误");
            }
            if ("0".equals(oprType)) {
                //802行不调用打款接口
                if (!"1".equals(skipPub)) {
                    // 调用营销打款接口
                    QueryCashierCashbackMcDetailInfoRequest queryRequestParam = new QueryCashierCashbackMcDetailInfoRequest();
                    queryRequestParam.setQueryType(param.getQueryType());
                    queryRequestParam.setQueryRole(param.getQueryRole());
                    queryRequestParam.setMcNo(param.getMcNo());
                    // 根据营销编号查询详情信息
                    Result<QueryCashierCashbackMcDetailInfoResponse> queryResponse = cashierService.getCashierMCDetail(queryRequestParam);
                    if (!queryResponse.isSuccess()) {
                        throw new RedpException("营销活动数据查询失败");
                    }
                    OperationResult paymentResult = customerMarketService.mompPayment(queryResponse.getResult().getMcInfoObj().getMcNo(), param.getAcctInfoObk(), user, queryResponse.getResult().getMcInfoObj().getBudget());
                    if (!OperationResult.SUCCESS.equals(paymentResult.getCode())) {
                        log.error("调用营销打款接口失败");
                        throw new RedpException("调用营销打款接口失败，请联系管理员");
                    }
                }
            }
            // 调用发布接口
            result = cashierService.publishCashierAgentMarket(param);
            if (null == result || null == result.getResult()) {
                log.error(resMs + "营销活时系统异常接口调用失败:result=[{}]", JSON.toJSONString(result));
                return OperationResult.buildFailureResult(resMs + "营销活动时系统异常接口调用失败");
            }
            if (!BusinessContainer.BSPS_SUCCESS.equals(result.getResult().getRespCode())) {
                log.error(resMs + "营销活动失败:code=[{}],msg=[{}]", result.getResult().getRespCode(), result.getResult().getRespDesc());
                return OperationResult.buildFailureResult(resMs + "营销活动失败:" + result.getResult().getRespDesc());
            }
        } catch (Exception e) {
            log.error("审核营销活动时系统异常:[{}]", e);
            return OperationResult.buildFailureResult(resMs + "营销活动时系统异常");
        }
        return OperationResult.buildSuccessResult(resMs + "营销活动操作成功");
    }

    //终止
//    @RequiresPermissions("银行对收银员营销活动发布:终止")
    @ResponseBody
    @RequestMapping(value = "/cashierShutdown", method = RequestMethod.POST)
    public OperationResult cashierShutdown(HttpServletRequest request) {
        Result<PublishCashierCashbackMcResponse> result = new Result<>();
        PublishCashierCashbackMcRequest param = new PublishCashierCashbackMcRequest();
        String resMs = "终止";
        try {
            param.setQueryType("0");
            //  02-发布
            param.setQueryRole("02");
            param.setMcNo(request.getParameter("mcNo"));
            param.setOprType(request.getParameter("oprType"));
            param.setOprContent(request.getParameter("oprContent"));
            // 账户信息
            McBankAccountInfoBean accountInfoBean = new McBankAccountInfoBean();
            accountInfoBean.setPayAcctNo(request.getParameter("payAcctNo"));
            //accountInfoBean.setPayAcctName(request.getParameter("payAcctName"));
            accountInfoBean.setIdType(request.getParameter("idType"));
            accountInfoBean.setIdNo(request.getParameter("idNo"));
            accountInfoBean.setCellPhoneNumber(request.getParameter("cellPhoneNumber"));
            accountInfoBean.setPicCapcha(request.getParameter("picCapcha"));
            accountInfoBean.setSmsCapcha(request.getParameter("smsCapcha"));
            param.setAcctInfoObk(accountInfoBean);


            // 调用发布接口
            result = cashierService.publishCashierAgentMarket(param);
            if (null == result || null == result.getResult()) {
                log.error(resMs + "营销活时系统异常接口调用失败:result=[{}]", JSON.toJSONString(result));
                return OperationResult.buildFailureResult(resMs + "营销活动时系统异常接口调用失败");
            }
            if (!BusinessContainer.BSPS_SUCCESS.equals(result.getResult().getRespCode())) {
                log.error(resMs + "营销活动失败:code=[{}],msg=[{}]", result.getResult().getRespCode(), result.getResult().getRespDesc());
                return OperationResult.buildFailureResult(resMs + "营销活动失败:" + result.getResult().getRespDesc());
            }
        } catch (Exception e) {
            log.error("审核营销活动时系统异常:[{}]", e);
            return OperationResult.buildFailureResult(resMs + "营销活动时系统异常");
        }
        return OperationResult.buildSuccessResult(resMs + "营销活动操作成功");
    }

    //暂停
//    @RequiresPermissions("银行对收银员营销活动发布:暂停")
    @ResponseBody
    @RequestMapping(value = "/cashierPause", method = RequestMethod.POST)
    public OperationResult cashierPause(HttpServletRequest request) {
        Result<PublishCashierCashbackMcResponse> result = new Result<>();
        PublishCashierCashbackMcRequest param = new PublishCashierCashbackMcRequest();
        String resMs = "暂停";
        try {
            param.setQueryType("0");
            //  02-发布
            param.setQueryRole("02");
            param.setMcNo(request.getParameter("mcNo"));
            param.setOprType(request.getParameter("oprType"));
            param.setOprContent(request.getParameter("oprContent"));
            // 账户信息
            McBankAccountInfoBean accountInfoBean = new McBankAccountInfoBean();
            accountInfoBean.setPayAcctNo(request.getParameter("payAcctNo"));
            //accountInfoBean.setPayAcctName(request.getParameter("payAcctName"));
            accountInfoBean.setIdType(request.getParameter("idType"));
            accountInfoBean.setIdNo(request.getParameter("idNo"));
            accountInfoBean.setCellPhoneNumber(request.getParameter("cellPhoneNumber"));
            accountInfoBean.setPicCapcha(request.getParameter("picCapcha"));
            accountInfoBean.setSmsCapcha(request.getParameter("smsCapcha"));
            param.setAcctInfoObk(accountInfoBean);


            // 调用发布接口
            result = cashierService.publishCashierAgentMarket(param);
            if (null == result || null == result.getResult()) {
                log.error(resMs + "营销活时系统异常接口调用失败:result=[{}]", JSON.toJSONString(result));
                return OperationResult.buildFailureResult(resMs + "营销活动时系统异常接口调用失败");
            }
            if (!BusinessContainer.BSPS_SUCCESS.equals(result.getResult().getRespCode())) {
                log.error(resMs + "营销活动失败:code=[{}],msg=[{}]", result.getResult().getRespCode(), result.getResult().getRespDesc());
                return OperationResult.buildFailureResult(resMs + "营销活动失败:" + result.getResult().getRespDesc());
            }
        } catch (Exception e) {
            log.error("审核营销活动时系统异常:[{}]", e);
            return OperationResult.buildFailureResult(resMs + "营销活动时系统异常");
        }
        return OperationResult.buildSuccessResult(resMs + "营销活动操作成功");
    }

    //启用
//    @RequiresPermissions("银行对收银员营销活动发布:启用")
    @ResponseBody
    @RequestMapping(value = "/cashierResume", method = RequestMethod.POST)
    public OperationResult cashierResume(HttpServletRequest request) {
        Result<PublishCashierCashbackMcResponse> result = new Result<>();
        PublishCashierCashbackMcRequest param = new PublishCashierCashbackMcRequest();
        String resMs = "启用";
        try {
            param.setQueryType("0");
            //  02-发布
            param.setQueryRole("02");
            param.setMcNo(request.getParameter("mcNo"));
            param.setOprType(request.getParameter("oprType"));
            param.setOprContent(request.getParameter("oprContent"));
            // 账户信息
            McBankAccountInfoBean accountInfoBean = new McBankAccountInfoBean();
            accountInfoBean.setPayAcctNo(request.getParameter("payAcctNo"));
            //accountInfoBean.setPayAcctName(request.getParameter("payAcctName"));
            accountInfoBean.setIdType(request.getParameter("idType"));
            accountInfoBean.setIdNo(request.getParameter("idNo"));
            accountInfoBean.setCellPhoneNumber(request.getParameter("cellPhoneNumber"));
            accountInfoBean.setPicCapcha(request.getParameter("picCapcha"));
            accountInfoBean.setSmsCapcha(request.getParameter("smsCapcha"));
            param.setAcctInfoObk(accountInfoBean);


            // 调用发布接口
            result = cashierService.publishCashierAgentMarket(param);
            if (null == result || null == result.getResult()) {
                log.error(resMs + "营销活时系统异常接口调用失败:result=[{}]", JSON.toJSONString(result));
                return OperationResult.buildFailureResult(resMs + "营销活动时系统异常接口调用失败");
            }
            if (!BusinessContainer.BSPS_SUCCESS.equals(result.getResult().getRespCode())) {
                log.error(resMs + "营销活动失败:code=[{}],msg=[{}]", result.getResult().getRespCode(), result.getResult().getRespDesc());
                return OperationResult.buildFailureResult(resMs + "营销活动失败:" + result.getResult().getRespDesc());
            }
        } catch (Exception e) {
            log.error("审核营销活动时系统异常:[{}]", e);
            return OperationResult.buildFailureResult(resMs + "营销活动时系统异常");
        }
        return OperationResult.buildSuccessResult(resMs + "营销活动操作成功");
    }

    public String genMerOrder(UpmpUserInfoVO user) {
        // 获取渠道ID：固定20
        String channelId = CommonUtils.getChannelId(upmpSysParamService, user.getInstId());
        // 代理商编码前缀：MO（merOrder简写）
        String prefix = user.getInstId() + "MCMP";
        // 自动生成一级代码
        String paramCode = BusinessContainer.COMM_PARAM_CODE;
        // 生成序列号
        String seqNum = sysSeqService.updateParamValue(paramCode, "MER_ORDER", channelId);
        // 8位日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String date8 = sdf.format(new Date());

        // 商户订单号
        String merOrder = prefix + date8 + String.format("%08d", Integer.parseInt(seqNum));
        return merOrder;
    }
}